package service.impl;

import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;

import security.MySecurityContextHandle;
import security.MyUserDetails;
import service.interf.IMember;
import service.interf.security.IAuthority;

import common.impl.CreateRandomCode;
import common.impl.MD5Transform;
import common.impl.SmsSender;
import common.impl.exception.ServiceException;

import dao.interf.IDeviceInfoDAO;
import dao.interf.IMemberDAO;
import dao.interf.IUserDAO;
import dao.pojo.Member;
import dao.pojo.User;

public class MemberImpl extends BaseDataServiceImpl implements IMember {

	private IMemberDAO memberDao;
	private IUserDAO userDao;
	private IAuthority iAuthority;
	private IDeviceInfoDAO deviceInfoDao;

	public void setMemberDao(IMemberDAO memberDao) {
		this.memberDao = memberDao;
	}

	public void setUserDao(IUserDAO userDao) {
		this.userDao = userDao;
	}

	public void setiAuthority(IAuthority iAuthority) {
		this.iAuthority = iAuthority;
	}

	public void setDeviceInfoDao(IDeviceInfoDAO deviceInfoDao) {
		this.deviceInfoDao = deviceInfoDao;
	}

	public String getHomeData(Long userId) throws Exception {
		// 用户
		Member member = memberDao.findById(userId);
		if (null == member)
			throw new ServiceException("请先登录");
		Date date = new Date();
		long time = date.getTime();
		time = time - 300000;
		Timestamp ts = new Timestamp(time);
		Long total_online;
		Long total_offline;
		if ("admin".equals(member.getUserName())) {
			// 在线设备
			String[] pNames = new String[] { "deviceActiveLast" };
			Object[] pValues = new Object[] { ts };
			String[] relations = new String[] { ">" };
			total_online = deviceInfoDao.getPropertiesCount(pNames, pValues,
					relations, null);
			// 离线设备
			pNames = new String[] { "deviceActiveLast" };
			pValues = new Object[] { ts };
			relations = new String[] { "<" };
			total_offline = deviceInfoDao.getPropertiesCount(pNames, pValues,
					relations, null);
		} else {
			// String deviceBindCode = member.getDeviceBindCode();
			String deviceBindCode = member.getUserName();
			// 在线设备
			String[] pNames = new String[] { "deviceBindCode",
					"deviceActiveLast" };
			Object[] pValues = new Object[] { deviceBindCode, ts };
			String[] relations = new String[] { "=", ">" };
			total_online = deviceInfoDao.getPropertiesCount(pNames, pValues,
					relations, null);
			// 离线设备
			pNames = new String[] { "deviceBindCode", "deviceActiveLast" };
			pValues = new Object[] { deviceBindCode, ts };
			relations = new String[] { "=", "<" };
			total_offline = deviceInfoDao.getPropertiesCount(pNames, pValues,
					relations, null);
		}
		JSONObject jo = new JSONObject();
		if (null == total_online)
			total_online = 0L;
		jo.put("total_online", total_online);
		if (null == total_offline)
			total_offline = 0L;
		jo.put("total_offline", total_offline);
		jo.put("total", total_offline + total_online);
		return jo.toString();
	}

	public String getMobileCodeForChangeMobile(String mobile) throws Exception {
		Long userId = MySecurityContextHandle.getUserId();
		Member member = memberDao.findById(userId);
		if (null == member)
			throw new ServiceException("请先登录");
		if(StringUtils.isEmpty(mobile))
			throw new ServiceException("请输入手机号");
		String mobile_old = member.getMobile();
		if(mobile.equals(mobile_old))
			throw new ServiceException("新手机号不能和原手机号一样");
		getMobileCode(mobile, "该手机号已被注册！");
		return "1";
	}

	public String getMobileCodeForRegister(String mobile) throws Exception {
		if(StringUtils.isEmpty(mobile))
			throw new ServiceException("请输入手机号");
		getMobileCode(mobile, "该手机号已被注册！请直接登录或换个手机号继续注册！");
		return "1";
	}

	private String getMobileCode(String mobile, String errors) throws Exception {
		long total = memberDao.getPropertiesCount(new String[]{"mobile"}, new Object[]{mobile}, null, null);
		if(total > 0)
			throw new ServiceException(errors);
		HttpSession session = ServletActionContext.getRequest().getSession();
		Object o = session.getAttribute("mobileCodeTime");
		if(null != o) {
			long time = Long.parseLong(o.toString());
			long time_now = new Date().getTime();
			if(time_now - time < 60000) {
				throw new ServiceException("获取验证码过于频繁，请稍后再试");
			}
		}
		session.setAttribute("mobile", mobile);
		String code = CreateRandomCode.getRandomNumString(6);
		SmsSender.sendSMSmethod(mobile, code);
		session.setAttribute("mobileCode", code);
		session.setAttribute("mobileCodeTime", new Date().getTime());
		return "1";
	}

	public String register(Member model, String mobileCode, String verifyCode,
			String password, String password2) throws Exception {
		// 验证验证码
		HttpSession session = ServletActionContext.getRequest().getSession();
		String verifyCode_s = (String) session.getAttribute("verifyCode");
		if (!verifyCode_s.equals(verifyCode))
			throw new ServiceException("验证码错误");
		// 验证手机验证码
		String mobile_s = (String) session.getAttribute("mobile");
		if (StringUtils.isEmpty(mobile_s))
			throw new ServiceException("请先获取手机验证码");
		String mobile = model.getMobile();
		if (!mobile_s.equals(mobile))
			throw new ServiceException("手机号错误");
		String mobileCode_s = (String) session.getAttribute("mobileCode");
		if (StringUtils.isEmpty(mobileCode_s))
			throw new ServiceException("请先获取手机验证码");
		if (!mobileCode_s.equals(mobileCode))
			throw new ServiceException("手机验证码错误");
		// 验证密码
		if (StringUtils.isEmpty(password))
			throw new ServiceException("密码不能为空");
		if (!password.equals(password2))
			throw new ServiceException("密码和确认密码不一致");
		// 验证码用户名
		String userName = model.getUserName();
		if (StringUtils.isEmpty(userName))
			throw new ServiceException("用户名不能为空");
		long total = userDao.getPropertiesCount(new String[] { "userName" },
				new Object[] { userName }, null, null);
		if (total > 0)
			throw new ServiceException("用户名已存在");
		// 添加用户
		User user = new User();
		user.setUserName(userName);
		user.setPassword(MD5Transform.EncoderByMd5(password, "utf8"));
		user.setEnabled((short) 1);
		userDao.save(user);
		Member member = new Member();
		member.setUser(user);
		member.setUserId(user.getUserId());
		member.setUserName(userName);
		member.setMobile(mobile);
		// String deviceBindCode;
		// do {
		// deviceBindCode = CreateRandomCode.getRandomString(12);
		// total = memberDao.getPropertiesCount(
		// new String[] { "deviceBindCode" },
		// new Object[] { deviceBindCode }, null, null);
		// } while (total > 0);
		// member.setDeviceBindCode(deviceBindCode);
		member.setRegTime(myDateHandle.getCurrentDTString());
		memberDao.save(member);
		// 用户组
		iAuthority.addUserToGroup(user.getUserId(), "agent");
		return "1";
	}

	public String getMobileCodeByUserName(String userName) throws Exception {
		if (StringUtils.isEmpty(userName))
			throw new ServiceException("请输入您需要找回的帐号或注册手机号");
		List<Member> memberL = memberDao.findByProperties(
				new String[] { "mobile" }, new Object[] { userName });
		if (null == memberL || memberL.isEmpty()) {
			memberL = memberDao.findByProperties(
					new String[] { "userName" }, new Object[] { userName });
			if (null == memberL || memberL.isEmpty()) {
				throw new ServiceException("该帐号或手机号未被注册");
			}
		}
		Member member = memberL.get(0);
		String mobile = member.getMobile();
		HttpSession session = ServletActionContext.getRequest().getSession();
		Object o = session.getAttribute("mobileCodeTime");
		if(null != o) {
			long time = Long.parseLong(o.toString());
			long time_now = new Date().getTime();
			if(time_now - time < 60000) {
				throw new ServiceException("获取验证码过于频繁，请稍后再试");
			}
		}
		session.setAttribute("mobile", mobile);
		String code = CreateRandomCode.getRandomNumString(6);
		SmsSender.sendSMSmethod(mobile, code);
		session.setAttribute("mobileCode", code);
		session.setAttribute("mobileCodeTime", new Date().getTime());
		return "1";
	}

	public String forgetpwd(Member model, String mobileCode, String verifyCode,
			String password, String password2) throws Exception {
		// 验证验证码
		HttpSession session = ServletActionContext.getRequest().getSession();
		String verifyCode_s = (String) session.getAttribute("verifyCode");
		if (!verifyCode_s.equals(verifyCode))
			throw new ServiceException("验证码错误");
		// 验证码用户名
		String userName = model.getUserName();
		if (StringUtils.isEmpty(userName))
			throw new ServiceException("请输入您需要找回的帐号或注册手机号");
		List<Member> memberL = memberDao.findByProperties(
				new String[] { "mobile" }, new Object[] { userName });
		if (null == memberL || memberL.isEmpty()) {
			memberL = memberDao.findByProperties(
					new String[] { "userName" }, new Object[] { userName });
			if (null == memberL || memberL.isEmpty()) {
				throw new ServiceException("该帐号或手机号未被注册");
			}
		}
		Member member = memberL.get(0);
		// 验证手机验证码
		String mobileCode_s = (String) session.getAttribute("mobileCode");
		if (StringUtils.isEmpty(mobileCode_s))
			throw new ServiceException("请先获取手机验证码");
		if (!mobileCode_s.equals(mobileCode))
			throw new ServiceException("手机验证码错误");
		// 验证密码
		if (StringUtils.isEmpty(password))
			throw new ServiceException("密码不能为空");
		if (!password.equals(password2))
			throw new ServiceException("密码和确认密码不一致");
		// 添加用户
		User user = member.getUser();
		if (null == user) {
			user = new User();
			user.setUserName(userName);
			user.setPassword(MD5Transform.EncoderByMd5(password, "utf8"));
			user.setEnabled((short) 1);
			userDao.save(user);
		} else {
			user.setPassword(MD5Transform.EncoderByMd5(password, "utf8"));
			userDao.update(user);
		}
		return "1";
	}

	public String changePwd(Long userId, String oldpwd, String password,
			String password2, String verifyCode) throws Exception {
		// 验证验证码
		HttpSession session = ServletActionContext.getRequest().getSession();
		String verifyCode_s = (String) session.getAttribute("verifyCode");
		if (!verifyCode_s.equals(verifyCode))
			throw new ServiceException("验证码错误");
		// 用户
		Member member = memberDao.findById(userId);
		if (null == member)
			throw new ServiceException("请先登录");
		User user = member.getUser();
		// 旧密码
		if (StringUtils.isEmpty(oldpwd))
			throw new ServiceException("旧密码不能为空");
		String oldpwd_md5 = user.getPassword();
		oldpwd = MD5Transform.EncoderByMd5(oldpwd, "utf8");
		if (!oldpwd.equals(oldpwd_md5))
			throw new ServiceException("旧密码错误");
		// 新密码
		if (StringUtils.isEmpty(password))
			throw new ServiceException("新密码不能为空");
		if (!password.equals(password2))
			throw new ServiceException("新密码和确认密码不一致");
		if (password.equals(oldpwd))
			throw new ServiceException("新密码不能和旧密码相同");
		// 修改
		user.setPassword(MD5Transform.EncoderByMd5(password, "utf8"));
		userDao.update(user);
		return "1";
	}

	public String changeMobile(Long userId, String mobile, String mobileCode,
			String verifyCode) throws Exception {
		// 验证验证码
		HttpSession session = ServletActionContext.getRequest().getSession();
		String verifyCode_s = (String) session.getAttribute("verifyCode");
		if (!verifyCode_s.equals(verifyCode))
			throw new ServiceException("验证码错误");
		// 用户
		Member member = memberDao.findById(userId);
		if (null == member)
			throw new ServiceException("请先登录");
		// 手机号
		if (StringUtils.isEmpty(mobile))
			throw new ServiceException("手机号不能为空");
		if (mobile.equals(member.getMobile()))
			throw new ServiceException("新手机号不能和旧手机号相同");
		String mobile_s = (String) session.getAttribute("mobile");
		if (StringUtils.isEmpty(mobile_s))
			throw new ServiceException("请先获取手机验证码");
		if (!mobile_s.equals(mobile))
			throw new ServiceException("手机号错误");
		String mobileCode_s = (String) session.getAttribute("mobileCode");
		if (StringUtils.isEmpty(mobileCode_s))
			throw new ServiceException("请先获取手机验证码");
		if (!mobileCode_s.equals(mobileCode))
			throw new ServiceException("手机验证码错误");
		// 修改
		member.setMobile(mobile);
		memberDao.update(member);
		return "1";
	}

}
